package com.glink.manage.service.Impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.domain.RoleMenuRelaBean;
import com.glink.manage.dto.role.RoleMenuIdListRequestDTO;
import com.glink.manage.dto.role.RoleMenuIdRequestDTO;
import com.glink.manage.mapper.RoleMenuRelaMapper;
import com.glink.manage.service.MenuService;
import com.glink.manage.service.RoleMenuRelaService;
import com.glink.manage.service.UserRoleRelaService;
import com.glink.manage.vo.menu.MenuBranchVO;
import com.glink.manage.vo.menu.MenuSimpleInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @class: RoleMenuRelaServiceImpl
 * @author: qiushaoshan
 * @since: 2025-01-07
 * @description:
 */
@Service
@Slf4j
public class RoleMenuRelaServiceImpl extends ServiceImpl<RoleMenuRelaMapper, RoleMenuRelaBean> implements RoleMenuRelaService {

    @Autowired
    private MenuService menuService;
    
    @Autowired
    private UserRoleRelaService userRoleRelaService;

    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean modifyRoleMenuRela(RoleMenuIdListRequestDTO dto) {

        List<String> menuIdList = dto.getMenuIdList();
        String roleId = dto.getRoleId();
        List<RoleMenuRelaBean> menuRelaBeanList;
        if (StringUtils.isNotBlank(roleId)) {
            this.lambdaUpdate()
                    .eq(RoleMenuRelaBean::getRoleId, roleId)
                    .remove();
            if (CollectionUtils.isNotEmpty(menuIdList)) {
                menuRelaBeanList = menuIdList.stream()
                        .map(menuId -> new RoleMenuRelaBean(BaseCommonUtils.generateUUID(), roleId, menuId))
                        .collect(Collectors.toList());
                log.info("新增修改权限:{}", JSON.toJSONString(menuRelaBeanList));
                return this.saveBatch(menuRelaBeanList);
            }
        }
        return false;
    }

//    @Override
//    public List<RoleBean> getRoleByResourceId(String resourceId) {
//        return baseMapper.getRoleByResourceId(resourceId);
//    }
//
//    @Override
//    public List<MenuBean> getResourceByRoleId(String roleId) {
//        return baseMapper.getResourceByRoleId(roleId);
//    }
//
//    @Override
//    public int deleteRoleResourceByResourceId(String resourceId) {
//        return getBaseMapper().delete(
//                Wrappers.lambdaQuery(RoleMenuRelaBean.class)
//                        .eq(RoleMenuRelaBean::getMenuId, resourceId)
//        );
//    }
//
//    @Override
//    public int deleteRoleResourceByRoleId(String roleId) {
//        return getBaseMapper().delete(
//                Wrappers.lambdaQuery(RoleMenuRelaBean.class)
//                        .eq(RoleMenuRelaBean::getRoleId, roleId)
//        );
//    }

    @Override
    public List<MenuSimpleInfoVO> findByRoleId(String roleId) throws GeneralSimpleException {

        // 查询角色对应的菜单ID
        List<String> menuIdList = this.lambdaQuery().eq(RoleMenuRelaBean::getRoleId, roleId).select(RoleMenuRelaBean::getMenuId)
                .list().stream().map(RoleMenuRelaBean::getMenuId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(menuIdList)){
            List<MenuSimpleInfoVO> simpleInfoVOList = menuService.getMenuList(menuIdList);
            if(CollectionUtils.isNotEmpty(simpleInfoVOList)){
                return simpleInfoVOList;
            }
        }

        return null;
    }

    /**
     * 根据用户ID获取菜单信息
     *
     * @param userId 用户ID
     * @return 菜单信息
     */
    @Override
    public List<MenuBranchVO> getAuthMenu(String userId) {
        // 查询这个人的角色信息
        List<String> roleIdList = userRoleRelaService.findRoleIdByUserId(userId);
        if(CollectionUtils.isNotEmpty(roleIdList)){
            // 查询分配的角色有哪些菜单
            List<RoleMenuRelaBean> roleMenuRelaBeanList = this.lambdaQuery()
                    .in(RoleMenuRelaBean::getRoleId, roleIdList)
                    .list();
            if(CollectionUtils.isNotEmpty(roleMenuRelaBeanList)){
                List<String> menuIdList = roleMenuRelaBeanList.stream().map(RoleMenuRelaBean::getMenuId).distinct().collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(menuIdList)){
                    return menuService.findAllMenuListById(menuIdList);
                }
            }
        }
        return null;
    }

    /**
     * 删除角色菜单关系
     *
     * @param roleId 角色Id
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteByRoleId(String roleId) {
        this.lambdaUpdate().eq(RoleMenuRelaBean::getRoleId, roleId).remove();
    }

    /**
     * 修改角色菜单的关系（单个）
     *
     * @param dto 修改的数据
     * @return 修改的状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean modifyRoleMenuRelaOne(RoleMenuIdRequestDTO dto) {
        if(Objects.nonNull(dto.getIsAdd())){
           
            RoleMenuRelaBean roleMenuRelaBean = this.lambdaQuery()
                    .eq(RoleMenuRelaBean::getRoleId, dto.getRoleId())
                    .eq(RoleMenuRelaBean::getMenuId, dto.getMenuId())
                    .one();
            if(dto.getIsAdd()){
                // 如果不存在，则新增
                if(Objects.isNull(roleMenuRelaBean)){
                    RoleMenuRelaBean relaBean = new RoleMenuRelaBean();
                    relaBean.setId(BaseCommonUtils.generateUUID());
                    relaBean.setRoleId(dto.getRoleId());
                    relaBean.setMenuId(dto.getMenuId());
                    save(relaBean);
                }
            }else{
                // 如果存在，则删除
                if(Objects.nonNull(roleMenuRelaBean)){
                    this.lambdaUpdate()
                            .eq(RoleMenuRelaBean::getRoleId, dto.getRoleId())
                            .eq(RoleMenuRelaBean::getMenuId, dto.getMenuId())
                            .remove();
                }
            }
            
        }
        return false;
    }

    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveRelaByRoleIdAndMenuId(List<String> roleIdList, String menuId) {
        if(CollectionUtils.isNotEmpty(roleIdList) && StringUtils.isNotEmpty(menuId)){
            this.lambdaUpdate().in(RoleMenuRelaBean::getRoleId, roleIdList).eq(RoleMenuRelaBean::getMenuId, menuId).remove();
            List<RoleMenuRelaBean> roleMenuRelaBeanList = Lists.newArrayList();
            roleIdList.forEach(roleId -> {
                RoleMenuRelaBean roleMenuRelaBean = new RoleMenuRelaBean();
                roleMenuRelaBean.setId(BaseCommonUtils.generateUUID());
                roleMenuRelaBean.setRoleId(roleId);
                roleMenuRelaBean.setMenuId(menuId);
                roleMenuRelaBeanList.add(roleMenuRelaBean);
            });
            
            if(CollectionUtils.isNotEmpty(roleMenuRelaBeanList)){
                saveBatch(roleMenuRelaBeanList);
            }
        }
    }

    /**
     * 根据菜单ID删除角色菜单关系
     *
     * @param menuId 菜单ID
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteByMenuId(String menuId) {
        this.lambdaUpdate().eq(RoleMenuRelaBean::getMenuId, menuId).remove();
    }
}
